package com.exception;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.log4j.Logger;

/**
 * @author murali
 */
public class ApplicationExceptionHandler extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final Logger logger = Logger.getLogger(this.getClass().getName());

    // Method to handle GET method request.
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        String servletName = (String) request.getAttribute("javax.servlet.error.servlet_name");

        if (servletName == null) {
            servletName = "Unknown Servlet";
        }

        String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");

        if (requestUri == null) {
            requestUri = "Unknown Request URI";
        }

        // Set response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String title = "Unexpected Error";
        String docType = "<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\">\n";

        out.println(docType + "<html><head><title>\n" + title + "</title></head><body bgcolor=\"#f0f0f0\">\n");
        if (throwable == null && statusCode == null) {
            out.println("Some Issue Occurred Unexpectedly. Try after few minutes");
            logger.debug("Error information is missing");
        } else if (statusCode != null) {
            out.println("Some Issue Occurred Unexpectedly. Try after few minutes");
            logger.error("Servlet Name : " + servletName);
            logger.error("Exception Type :" + throwable.getClass().getName());
            logger.error("The request URI: " + requestUri);
            logger.error("The exception message: " + throwable.getMessage());
        } else {
            logger.error("Servlet Name : " + servletName);
            logger.error("Exception Type :" + throwable.getClass().getName());
            logger.error("The request URI: " + requestUri);
            logger.error("The exception message: " + throwable.getMessage());
            out.println("Some Issue Occurred Unexpectedly. Try after few minutes");
        }
        out.println("</body>");
        out.println("</html>");
    }

    // Method to handle POST method request.
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}